package com.miao.im.support.util;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/11 15:33
 * @Description:
 */
@Slf4j
public class MachineIdUtil {
    public static final String DELIMITER = ":";
    private volatile static String localId = "";
    private static final SymmetricCrypto AES = new SymmetricCrypto(SymmetricAlgorithm.AES, new byte[]{
            127, 76, 68, 11, -64, -19, -9, 122, -120, -41, -86, 16, 24, 85, -4, 39
    });

    /**
     * 创建一个特别的本机id
     * @author miaoguoxin
     * @date 2021/3/11
     */
    public static String encryptLocalMachineId() {
        if (StrUtil.isBlank(localId)) {
            synchronized (AES) {
                if (StrUtil.isBlank(localId)) {
                    localId = createId();
                }
            }
        }
        return localId;
    }

    /**
    * 解密机器的id
    * @author miaoguoxin
    * @date 2021/3/15
    */
    public static String decryptLocalMachinedId(String encryptId){
        return AES.decryptStr(encryptId);
    }

    /**
    *  session是否是本机地址
    * @author miaoguoxin
    * @date 2021/3/15
    */
    public static boolean sessionIdIsLocalMachine(String sessionId){
        if (StrUtil.isBlank(sessionId)){
            return false;
        }
        String[] strs = sessionId.split(DELIMITER);
        if (strs.length != 2){
            return false;
        }
        return encryptLocalMachineId().equals(strs[1]);
    }

    private static String createId() {
        try {
            InputStream inputStream = ResourceUtil.getStream("application.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            InetAddress addr = InetAddress.getLocalHost();
            return AES.encryptHex(addr.getHostAddress() + ":" + properties.getProperty("server.port"));
        } catch (UnknownHostException e) {
            log.error("获取本机ip失败", e);
        } catch (IOException e) {
            log.error("读取文件失败", e);
        }
        return null;
    }
}
